package com.youlai.boot.system.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.common.util.ExcelUtils;
import com.youlai.boot.system.model.dto.LedgerCountVO;
import com.youlai.boot.system.model.form.SysLedgerForm;
import com.youlai.boot.system.model.query.SysLedgerQuery;
import com.youlai.boot.system.model.vo.SysLedgerExcelVO;
import com.youlai.boot.system.model.vo.SysLedgerVO;
import com.youlai.boot.system.service.SysLedgerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 流水台账前端控制层
 *
 * @author youlaitech
 * @since 2025-05-12 15:55
 */
@Tag(name = "流水台账接口")
@RestController
@RequestMapping("/api/v1/sysLedgers")
@RequiredArgsConstructor
public class SysLedgerController  {

    private final SysLedgerService sysLedgerService;

    @Operation(summary = "流水台账分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('system:sysLedger:query')")
    public PageResult<SysLedgerVO> getSysLedgerPage(SysLedgerQuery queryParams ) {
        IPage<SysLedgerVO> result = sysLedgerService.getSysLedgerPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "流水台账统计")
    @GetMapping("/count")
    @PreAuthorize("@ss.hasPerm('system:sysLedger:query')")
    public Result<LedgerCountVO> getSysLedgerCount(SysLedgerQuery queryParams ) {
        LedgerCountVO result = sysLedgerService.getSysLedgerCount(queryParams);
        return Result.success(result);
    }

    @Operation(summary = "新增流水台账")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('system:sysLedger:add')")
    public Result<Void> saveSysLedger(@RequestBody @Valid SysLedgerForm formData ) {
        boolean result = sysLedgerService.saveSysLedger(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取流水台账表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('system:sysLedger:edit')")
    public Result<SysLedgerForm> getSysLedgerForm(
        @Parameter(description = "流水台账ID") @PathVariable Long id
    ) {
        SysLedgerForm formData = sysLedgerService.getSysLedgerFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改流水台账")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:sysLedger:edit')")
    public Result<Void> updateSysLedger(
            @Parameter(description = "流水台账ID") @PathVariable Long id,
            @RequestBody @Validated SysLedgerForm formData
    ) {
        boolean result = sysLedgerService.updateSysLedger(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除流水台账")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:sysLedger:delete')")
    public Result<Void> deleteSysLedgers(
        @Parameter(description = "流水台账ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = sysLedgerService.deleteSysLedgers(ids);
        return Result.judge(result);
    }

    @Operation(summary = "导出流水台账")
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPerm('system:sysLedger:export')")
    public void export(SysLedgerQuery queryParams, HttpServletResponse response) throws IOException {

        List<SysLedgerExcelVO> list = sysLedgerService.exportList(queryParams);

        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/export.xlsx");
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+"流水台账.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }
}
